import requests
import os

from lxml import etree

# 将请求头定义为常量
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36'

def create_dir(singer_name):
    # 创建音乐目录，如果不存在的话
    singer_name_safe = singer_name.replace('/', '_').replace('\\', '_')
    directory = f"./music/{singer_name_safe}"
    os.makedirs(directory, exist_ok=True)
    return directory


def download_music(singer_name, singer_id, down_musics):
    headers = {'user-agent': USER_AGENT}

    # id 是对应的歌手，比如2116--陈奕迅
    url = 'https://music.163.com/artist?id=' + singer_id

    demo = requests.get(url, headers=headers)

    data = etree.HTML(demo.text)

    e = data.xpath('//a[contains(@href,"/song?")]')

    for music in e:
        href = music.xpath('./@href')[0]
        music_id = href.split('=')[1]
        # 获取音乐名称，如果列表为空则跳过本次循环
        music_texts = music.xpath('./text()')
        if music_texts:
            music_name = music_texts[0]
        else:
            print(f"当前歌手音乐循环结束")
            return  # 跳过本次循环
        if down_musics is None:
            base_url = 'http://music.163.com/song/media/outer/url?id='
            music_content = requests.get(base_url + music_id)
            if music_content.status_code == 200:
                content_type = music_content.headers.get('Content-Type')
                if 'audio' not in content_type:
                    print(f"{music_name}----会员音乐，暂无法下载")
                    continue
            content = music_content.content
            directory = create_dir(singer_name)
            # 在相应目录下写入文件
            music_name_safe = music_name.replace('/', '_').replace('\\', '_')
            try:
                with open(os.path.join(directory, f'{music_name_safe}.mp3'), 'wb') as file:
                    file.write(content)
                    print(music_name_safe + '----下载完成')
            except Exception as e:
                print(f"Error occurred: {e}")
        else:
            if music_name in down_musics:
                # 下载音乐
                base_url = 'http://music.163.com/song/media/outer/url?id='
                music_content = requests.get(base_url + music_id)
                if music_content.status_code != 200:
                    print(f"{music_name}----下载失败，无法访问资源")
                    continue
                content = music_content.content
                content_type = music_content.headers.get('Content-Type')
                if 'audio' not in content_type:
                    print(f"{music_name}----会员音乐，暂无法下载")
                    continue
                    # 创建音乐目录，如果不存在的话
                directory = create_dir(singer_name)
                # 在相应目录下写入文件
                music_name_safe = music_name.replace('/', '_').replace('\\', '_')
                try:
                    with open(os.path.join(directory, f'{music_name_safe}.mp3'), 'wb') as file:
                        file.write(content)
                        print(music_name_safe + '----下载完成')
                except Exception as e:
                    print(f"Error occurred: {e}")
